package com.yonyou.iuap.shell.service.impl;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.Date;
import java.util.Map;

import org.apache.commons.net.ftp.FTPClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.yonyou.iuap.base.vo.FastDfsMsgVO;
import com.yonyou.iuap.pub.DateUtil;
import com.yonyou.iuap.pub.FastDFSFile;
import com.yonyou.iuap.pub.FileManager;
import com.yonyou.iuap.pub.IDFactory;
import com.yonyou.iuap.shell.dao.KmAttachmentEntityDao;
import com.yonyou.iuap.shell.entity.KmAttachmentEntity;
import com.yonyou.iuap.shell.entity.exp.ShellFileUpPoJo;
import com.yonyou.iuap.shell.pub.FileTypeUtils;
import com.yonyou.iuap.shell.pub.IShellDaoEnum;
import com.yonyou.iuap.shell.pub.IShellServiceEnum;
import com.yonyou.iuap.shell.pub.ShellFtpFileUtils;
import com.yonyou.iuap.shell.service.intf.IFtpService;
import com.yonyou.iuap.shell.service.intf.IKmFileManagerService;
@Service(value=IShellServiceEnum.Shell_Service_FillManager)
public class KmFileManagerServiceImpl implements IKmFileManagerService {

	@Autowired
	@Qualifier(IShellDaoEnum.Shell_Dao_KmAttachmentEntityDao)
	private KmAttachmentEntityDao attDao;
	@Autowired
	private IFtpService ftpService;
	private String groupNmae="group1";
	
	/**
	 * 文件上传
	 */
	public FastDfsMsgVO uploadFile(File file,ShellFileUpPoJo filePoJo) {
		
		FastDFSFile dfsFile = new FastDFSFile(file, null, filePoJo.getWidth(), filePoJo.getHeight(), filePoJo.getUp_user());
		FastDfsMsgVO msgvo = new FastDfsMsgVO();
		try {
			msgvo = FileManager.upload(dfsFile);
			//生成附件表信息
			if(msgvo.getStatus()==0){
				KmAttachmentEntity vo = new KmAttachmentEntity();
				vo.setPk_attachment(IDFactory.getInstance().getID());
				String[] fileNameArr = getFileNameAndHz(filePoJo.getFile_name());
				vo.setFname(filePoJo.getFile_name());
				vo.setFilename(groupNmae);
				vo.setSysfilename(filePoJo.getFile_hz());
				vo.setFileurl(msgvo.getUploadResult()[1]);
				vo.setFilesize(new BigDecimal(file.length()));
				vo.setUpload_type(FileTypeUtils.getFileType(filePoJo.getFile_hz()));
				vo.setPk_business(filePoJo.getPk_business());
				vo.setFile_measure((filePoJo.getWidth()==null?"":filePoJo.getWidth())+"*"+(filePoJo.getHeight()==null?"":filePoJo.getHeight()));
				vo.setPk_uploaduser(filePoJo.getUp_user());
				vo.setDtupload(DateUtil.formatDateTime(new Date()));
				vo.setDtcreate(new Date());
				vo.setDr(0);
				vo.setTs(DateUtil.formatDateTime(new Date()));
				attDao.insertSelective(vo);
				msgvo.setPk_att(vo.getPk_attachment());
			}
		} catch (IOException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
			msgvo.setMsg("上传失败："+e.getMessage());
			msgvo.setStatus(-1);
		}
		
		return msgvo;
	}
	private String[] getFileNameAndHz(String name){
		String[] str = new String[2];
		if(!StringUtils.isEmpty(name)){
			if(name.lastIndexOf(".")>=0){
				str[0] = name.substring(0,name.lastIndexOf("."));
				str[1] = name.substring(name.lastIndexOf(".")+1,name.length());
			}else{
				str[0]=name;
			}
		}
		return str;
	}
	public FastDfsMsgVO downFile(Map<String, String> map) {
		FastDfsMsgVO msgvo = new FastDfsMsgVO();
		String att_pk = map.get("pk_att");
		KmAttachmentEntity vo = (KmAttachmentEntity) attDao.selectByPrimaryKey(att_pk);
		if(vo==null){
			msgvo.setStatus(-1);
			msgvo.setMsg("未查询到文件信息!");
		}else{
			byte[] file_content;
			try {
				msgvo.setFile_name(vo.getFname());
				msgvo.setFile_hz(vo.getSysfilename());
				file_content = FileManager.downFile(groupNmae, vo.getFileurl());
				msgvo.setStatus(0);
				msgvo.setMsg("文件下载成功!");
				msgvo.setB_file(file_content);
			} catch (Exception e) {
				msgvo.setStatus(-1);
				msgvo.setMsg("文件下载失败："+e.getMessage());
			}
			
		}
		return msgvo;
	}

	public FastDfsMsgVO deleteFile(Map<String, String> map) {
		FastDfsMsgVO msgvo = new FastDfsMsgVO();
		String att_pk = map.get("pk_att");
		KmAttachmentEntity vo = (KmAttachmentEntity) attDao.selectByPrimaryKey(att_pk);
		if(vo==null){
			msgvo.setStatus(-1);
			msgvo.setMsg("未查询到文件信息!");
		}else{
			try {
				int i_rs = FileManager.deleteFile(groupNmae, vo.getFileurl());
				if(i_rs ==0 || i_rs==2){
					msgvo.setStatus(0);
					msgvo.setMsg("文件删除成功!");
				}else{
					msgvo.setStatus(i_rs);
					msgvo.setMsg("文件删除失败!");
				}
				
			} catch (Exception e) {
				msgvo.setStatus(-1);
				msgvo.setMsg("文件删除失败："+e.getMessage());
			}
			
		}
		return msgvo;
	}
	public FastDfsMsgVO uploadFile(byte[] bytes, ShellFileUpPoJo filePoJo) {
		
		FastDFSFile dfsFile = new FastDFSFile(bytes, filePoJo.getFile_name(),filePoJo.getFile_hz(), filePoJo.getWidth(), filePoJo.getHeight(), filePoJo.getUp_user());
		FastDfsMsgVO msgvo = new FastDfsMsgVO();
		try {
			msgvo = FileManager.upload(dfsFile);
			msgvo.setFile_type(FileTypeUtils.getFileType(filePoJo.getFile_hz()));
			//生成附件表信息
			if(msgvo.getStatus()==0){
				KmAttachmentEntity vo = new KmAttachmentEntity();
				vo.setPk_attachment(IDFactory.getInstance().getID());
				String[] fileNameArr = getFileNameAndHz(filePoJo.getFile_name());
				vo.setFname(filePoJo.getFile_name());
				vo.setFilename(groupNmae);
				vo.setSysfilename(filePoJo.getFile_hz());
				vo.setFileurl(msgvo.getUploadResult()[1]);
				vo.setFilesize(new BigDecimal(bytes.length));
				vo.setUpload_type(FileTypeUtils.getFileType(filePoJo.getFile_hz()));
				vo.setPk_business(filePoJo.getPk_business());
				vo.setFile_measure((filePoJo.getWidth()==null?"":filePoJo.getWidth())+"*"+(filePoJo.getHeight()==null?"":filePoJo.getHeight()));
				vo.setPk_uploaduser(filePoJo.getUp_user());
				vo.setDtupload(DateUtil.formatDateTime(new Date()));
				vo.setDtcreate(new Date());
				vo.setDr(0);
				vo.setTs(DateUtil.formatDateTime(new Date()));
				attDao.insertSelective(vo);
				msgvo.setPk_att(vo.getPk_attachment());
			}
		} catch (IOException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
			msgvo.setMsg("上传失败："+e.getMessage());
			msgvo.setStatus(-1);
		}
		
		return msgvo;
	}
	public FastDfsMsgVO uploadFileForFtp(ShellFileUpPoJo filePoJo) {
		
		FastDfsMsgVO msgvo = new FastDfsMsgVO();
		try {
			//上传文件
				msgvo.setFile_type(FileTypeUtils.getFileType(filePoJo.getFile_hz()));
				//生成附件表信息
				if(msgvo.getStatus()==0){
					KmAttachmentEntity vo = new KmAttachmentEntity();
					vo.setPk_attachment(IDFactory.getInstance().getID());
					String[] fileNameArr = getFileNameAndHz(filePoJo.getFile_name());
					vo.setFname(filePoJo.getFile_name());
					vo.setFilename(filePoJo.getFile_name()+"."+filePoJo.getFile_hz());
					vo.setSysfilename(filePoJo.getFile_hz());
					vo.setFileurl(filePoJo.getFileurl());//文件url
					vo.setFilesize(new BigDecimal(filePoJo.getFile_size()));
					vo.setUpload_type(FileTypeUtils.getFileType(filePoJo.getFile_hz()));
//					vo.setPk_business(filePoJo.getPk_business());
					vo.setFile_measure((filePoJo.getWidth()==null?"":filePoJo.getWidth())+"*"+(filePoJo.getHeight()==null?"":filePoJo.getHeight()));
//					vo.setPk_uploaduser(filePoJo.getUp_user());
					vo.setDtupload(DateUtil.formatDateTime(new Date()));
					vo.setDtcreate(new Date());
					vo.setDr(0);
					vo.setTs(DateUtil.formatDateTime(new Date()));
					vo.setStore_address(filePoJo.getFile_path());
					attDao.insertSelective(vo);
					msgvo.setPk_att(vo.getPk_attachment());
				}
				msgvo.setStatus(0);
				msgvo.setMsg("文件上传成功!");
			
		} catch (Exception e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
			msgvo.setMsg("上传失败："+e.getMessage());
			msgvo.setStatus(-1);
		}
		
		return msgvo;
	}
	public FastDfsMsgVO deleteFileForFtp(Map<String, String> map) {
		FastDfsMsgVO msgvo = new FastDfsMsgVO();
		String att_pk = map.get("pk_att");
		KmAttachmentEntity vo = (KmAttachmentEntity) attDao.selectByPrimaryKey(att_pk);
		FTPClient ftpClient = new FTPClient();
        try {
			if(vo==null){
				msgvo.setStatus(-1);
				msgvo.setMsg("未查询到文件信息!");
			}else{
				String pathName=vo.getFileurl().substring(vo.getFileurl().lastIndexOf("/")+1);
				boolean is_del = ftpService.delFile(ftpClient, pathName);//删除文件路径
				if(is_del){
					msgvo.setStatus(0);
					msgvo.setMsg("文件删除成功!");
				}else{
					msgvo.setStatus(-1);
					msgvo.setMsg("文件删除失败!");
				}
			}
		} catch (Exception e1) {
			e1.printStackTrace();
			msgvo.setStatus(-1);
			msgvo.setMsg("文件删除失败："+e1.getMessage());
		}
		
		return msgvo;
	}
	
	public FastDfsMsgVO deleteFileForTom(Map<String, String> map) {
		FastDfsMsgVO msgvo = new FastDfsMsgVO();
		String att_pk = map.get("pk_att");
		KmAttachmentEntity vo = (KmAttachmentEntity) attDao.selectByPrimaryKey(att_pk);
		if(vo==null){
			msgvo.setStatus(-1);
			msgvo.setMsg("未查询到文件信息!");
		}else{
			try {
				boolean is_del = deleteFile(vo.getStore_address());//删除文件路径
				if(is_del){
					msgvo.setStatus(0);
					msgvo.setMsg("文件删除成功!");
				}else{
					msgvo.setStatus(-1);
					msgvo.setMsg("文件删除失败!");
				}
				
			} catch (Exception e) {
				msgvo.setStatus(-1);
				msgvo.setMsg("文件删除失败："+e.getMessage());
			}
			
		}
		return msgvo;
	}
	public FastDfsMsgVO downFileForFtp(Map<String, String> map) {
		FastDfsMsgVO msgvo = new FastDfsMsgVO();
		String att_pk = map.get("pk_att");
		KmAttachmentEntity vo = (KmAttachmentEntity) attDao.selectByPrimaryKey(att_pk);
		if(vo==null){
			msgvo.setStatus(-1);
			msgvo.setMsg("未查询到文件信息!");
		}else{
				msgvo.setFile_name(vo.getFilename());
				msgvo.setFile_hz(vo.getSysfilename());
				msgvo.setStatus(0);
				msgvo.setFile_hz(vo.getSysfilename());
				msgvo.setFile_size(vo.getFilesize()==null?"0":vo.getFilesize().toString());
				msgvo.setFile_type(vo.getUpload_type());
				msgvo.setFile_url(vo.getFileurl());
		}
		return msgvo;
	}

    /**
     * 删除单个文件
     * @param   sPath    被删除文件的文件名
     * @return 单个文件删除成功返回true，否则返回false
     */
    public boolean deleteFile(String sPath) {
        boolean flag = false;
        File file = new File(sPath);
        // 路径为文件且不为空则进行删除
        if (file.isFile() && file.exists()) {
            file.delete();
            flag = true;
        }
        return flag;
    }
}
